package com.np.moneylover;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.np.dao.JSONParser;
import com.np.dao.KeHoachData;
import com.np.dao.KeHoachDataListener;
import com.np.dao.LoaiGiaoDichData;
import com.np.dao.LoaiGiaoDichDataListener;
import com.np.dto.KeHoach;
import com.np.dto.LoaiGiaoDich;
import com.np.moneylover.Thu.KeHoachSelected;
import com.np.moneylover.Thu.LoaGiaoDichSelected;
import com.np.moneylover.Thu.Thu_action;

import Util.Constants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class Chi extends Activity implements OnClickListener, LoaiGiaoDichDataListener, KeHoachDataListener {
	EditText txtkhoanchi=null;
	EditText txtsotien=null;
	EditText txtghichu=null;
	EditText txtngaychi=null;
	Spinner sptheloai=null;
	Spinner spkehoach=null;
	Button btnluuthem=null;
	Button btnluu=null;
	public List<LoaiGiaoDich>lstlgiaodich=null;
	public LoaiGiaoDich datalgdClick;
	public List<KeHoach>lstkehoach=null;
	public KeHoach dataLMClick;
	private Object dateFinish;
	private Calendar cal;
	public String mess;
	private String url1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.chi);
		txtkhoanchi=(EditText)findViewById(R.id.txtkhoanchi);
		txtsotien=(EditText)findViewById(R.id.txtsotienchi);
		txtghichu=(EditText)findViewById(R.id.txtghichuchi);
		txtngaychi=(EditText)findViewById(R.id.dtpngaychi);
		spkehoach=(Spinner)findViewById(R.id.spkehoachchi);
		sptheloai=(Spinner)findViewById(R.id.sptheloaichi);
		btnluuthem=(Button)findViewById(R.id.btnluuthemchi);
		btnluu=(Button)findViewById(R.id.btnluuchi);
		btnluuthem.setOnClickListener(this);
		btnluu.setOnClickListener(this);
		txtngaychi.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// Launching All products Activity
				showDatePickerDialog();
			}
		});
		Loadreference();
		
	}
	private void Loadreference() {
		// TODO Auto-generated method stub
		
		//1 load loai giao dich chi
		LoadLoaiGiaoDichChi();
		
		// set dong ho
		LoadDatatimeNow();
		
		// load ke hoach.
		LoadKehoach();
		
	}
	private void LoadDatatimeNow() {
		// TODO Auto-generated method stub
		
		// lấy ngày hiện tại của hệ thống
				cal = Calendar.getInstance();
				SimpleDateFormat dft = null;
				// Định dạng ngày / tháng /năm
				dft = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
				String strDate = dft.format(cal.getTime());
				// hiển thị lên giao diện
				txtngaychi.setText(strDate);

				dateFinish = cal.getTime();
		
	}
	
	public void showDatePickerDialog() {
		OnDateSetListener callback = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				txtngaychi.setText((arg3) + "/" + (arg2 + 1) + "/" + arg1);
				// Lưu vết lại biến ngày hoàn thành
				cal.set(arg1, arg2, arg3);
				dateFinish = cal.getTime();
			}
		};
		// các lệnh dưới này xử lý ngày giờ trong DatePickerDialog
		// sẽ giống với trên TextView khi mở nó lên

		String s = txtngaychi.getText() + "";
		String strArrtmp[] = s.split("/");
		int ngay = Integer.parseInt(strArrtmp[0]);
		int thang = Integer.parseInt(strArrtmp[1]) - 1;
		int nam = Integer.parseInt(strArrtmp[2]);
		DatePickerDialog pic = new DatePickerDialog(Chi.this, callback, nam,
				thang, ngay);
		pic.setTitle("Chọn ngày hoàn thành");
		pic.show();
	}

	/////////////////////////////////
	private void LoadLoaiGiaoDichChi() {
		// TODO Auto-generated method stub
		String url = "http://10.0.2.2:8080/connect_android/getloaigiaodich.php?magd=1";
		LoaiGiaoDichData task = new LoaiGiaoDichData(this);
		task.execute(url);
	}
	@Override
	public void onLoaiLoaiGiaoDichComplete(List<LoaiGiaoDich> data) {
		// TODO Auto-generated method stub
		lstlgiaodich = data;

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < lstlgiaodich.size(); i++) {
			String temp = lstlgiaodich.get(i).getTenLoaiGD().toString();
			list.add(temp);

		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sptheloai.setAdapter(dataAdapter);
		sptheloai.setOnItemSelectedListener(new LoaGiaoDichSelected());
		
	}
	@Override
	public void onLoaiGiaoDichFailure(String msg) {
		// TODO Auto-generated method stub
		
	}
	class LoaGiaoDichSelected implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			datalgdClick = lstlgiaodich.get(pos);

		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	}
	
	
	
	
	/////////////////////////////////////////////////////////////////////////////////
	private void LoadKehoach() {
		// TODO Auto-generated method stub

		String url = "http://10.0.2.2:8080/connect_android/getkehoach.php";
		KeHoachData task = new KeHoachData(this);
		task.execute(url);
	}
	@Override
	public void onGetListKeHoachComplete(List<KeHoach> data) {
		// TODO Auto-generated method stub
		lstkehoach = data;

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < lstkehoach.size(); i++) {
			String temp = lstkehoach.get(i).getTenKH().toString();
			list.add(temp);

		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spkehoach.setAdapter(dataAdapter);
		spkehoach.setOnItemSelectedListener(new KeHoachSelected());
		
	}
	@Override
	public void onGetListKeHoachFailure(String msg) {
		// TODO Auto-generated method stub
		
	}
	class KeHoachSelected implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			dataLMClick = lstkehoach.get(pos);

		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	}

	
	///////////////////////////////////////////////////////////////////////////////////
	

	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id=v.getId();
		switch (id) {
		case R.id.btnluuthemchi:

			if (invalid().equals("")) {
				url1 = "http://10.0.2.2:8080/connect_android/thuchi_them.php";
				Chi_action task = new Chi_action();
				task.execute(url1);
				if(mess.equals("1")){
				   Intent I= new Intent(this,GiaoDich.class);
				   startActivity(I);
						   
				}
				else
				{
					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
				    dlgAlert.setMessage("Thêm khoản chi không thành công");
				    dlgAlert.setTitle("Thông báo");              
				    dlgAlert.setPositiveButton("OK", null);
				    dlgAlert.setCancelable(false);
				    dlgAlert.create().show();
					
				}
			}
			else
			{
				AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
			    dlgAlert.setMessage(invalid());
			    dlgAlert.setTitle("Thông báo");              
			    dlgAlert.setPositiveButton("OK", null);
			    dlgAlert.setCancelable(false);
			    dlgAlert.create().show();
			}

			break;
        case R.id.btnluuchi:
        	
        	if (invalid().equals("")) {
				url1 = "http://10.0.2.2:8080/connect_android/thuchi_them.php";
				Chi_action task = new Chi_action();
				task.execute(url1);
				if(mess.equals("1")){
				   Intent I= new Intent(this,SoChiTieu.class);
				   startActivity(I);
						   
				}
				else
				{
					AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
				    dlgAlert.setMessage("Thêm khoản chi không thành công");
				    dlgAlert.setTitle("Thông báo");              
				    dlgAlert.setPositiveButton("OK", null);
				    dlgAlert.setCancelable(false);
				    dlgAlert.create().show();
					
				}
			}
			else
			{
				AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
			    dlgAlert.setMessage(invalid());
			    dlgAlert.setTitle("Thông báo");              
			    dlgAlert.setPositiveButton("OK", null);
			    dlgAlert.setCancelable(false);
			    dlgAlert.create().show();
			}

        	break;
		default:
			break;
		}
	}
	public String invalid() {
		String errors = "";
		if (txtkhoanchi.getText().equals("")) {
			errors += "\nKhoản thu chưa nhập";
		}
		if (txtsotien.getText().equals("")) {
			errors += "\nSố tiền chưa nhập";
		} else {
			try {
				Float.parseFloat(txtsotien.getText().toString());

			} catch (Exception e) {
				// TODO: handle exception
				errors += "\nSố tiền không hợp lệ";

			}
		}
		return errors;

	}
	class Chi_action extends AsyncTask<String, String, String> {
		ProgressDialog Pdialog = null;
		int success = 0;
		String msg = "";
		String test = "";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Pdialog = new ProgressDialog(Chi.this);
			Pdialog.setMessage("Đang thực hiện giao dịch..");
			Pdialog.setIndeterminate(false);
			Pdialog.setCancelable(true);
			Pdialog.show();
		}

		protected String doInBackground(String... params) {
			if (params == null)
				return null;
			JSONParser jsonParser = new JSONParser();
			// get url from params
			List<NameValuePair> arrays = new ArrayList<NameValuePair>();

			arrays.add(new BasicNameValuePair("tengd", txtkhoanchi.getText()
					.toString().trim()));
			arrays.add(new BasicNameValuePair("sotien", txtsotien.getText()
					.toString().trim()));
			arrays.add(new BasicNameValuePair("laplai", "0"));
			arrays.add(new BasicNameValuePair("ngaygd", "2013-8-9"));
			arrays.add(new BasicNameValuePair("ghichu", txtghichu.getText()
					.toString().trim()));
			arrays.add(new BasicNameValuePair("maloaigd", Integer
					.toString(datalgdClick.ID)));
			arrays.add(new BasicNameValuePair("magd", "2"));
			arrays.add(new BasicNameValuePair("username", Constants._login
					.getUser().toString()));
			arrays.add(new BasicNameValuePair("makh", Integer
					.toString(dataLMClick.ID)));

			JSONObject json = jsonParser.makeHttpRequest(url1, "POST", arrays);
			try {
				success = json.getInt("success");
				test = json.getString("message");

				/*if (success == 1) {
					// successfully created product

					msg = "thanhcong";
					return null;

				} else {
					// failed to create product
					msg = "That bai";
					return null;
				}*/
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			Pdialog.dismiss();

			if (success == 1) {
				
                mess="1";
			}
			else
			{
				mess="2";
			}

		}
	}


}
